<template>
  <div class="text">
      个人中心
  </div>
  <p>管理员ID:{{ userInfo.id }}</p>
  <p>账号:{{ userInfo.account }}</p>
  <p>用户组:{{ userInfo.userGroup }}</p>
  <!-- <p>创建日期:{{ userInfo.ctime.slice(0,10) }}</p> -->
  <p>创建日期:{{ formatTime(userInfo.ctime)}}</p>

  <div style="margin-top: -10px;">
      管理员头像: <el-upload
          class="avatar-uploader"
          :action="'/api/users/avatar_upload?id='+userInfo.id"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
      >
          <img v-if="userInfo.imgUrl" :src="serverUrl+userInfo.imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import dayjs from 'dayjs'
import { accountInfo } from '../../api/account';
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { serverUrl } from '@/utils/common'
import { userStore } from '@/stores/userStore' 
// const imageUrl = ref('')
const userInfo = ref({});
const store = userStore()

//使用 async/await 重构数据获取逻辑
const getAccountInfo = async () => {
  const user = JSON.parse(sessionStorage.getItem('user') || '{}'); // 安全解析
  if (user.id) {
    const res = await accountInfo({ id: user.id });
    userInfo.value = res.accountInfo;
  }
}
getAccountInfo(); // 立即执行

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size > 2 * 1024 * 1024) { // 1MB
    ElMessage.error('文件大小不能超过 1M'); 
  }
  if (!rawFile.type.includes('image')) {
    ElMessage.error('文件类型必须是图片'); 
    return false;
  }
  return true;
}

//简化 success 回调，移除冗余参数，直接调用 getAccountInfo
const handleAvatarSuccess: UploadProps['onSuccess'] = () => {
  getAccountInfo(); // 重新获取用户信息（含新头像地址）
  store.changeUserInfoState(); 
}

const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD');
}
</script>

<style scoped>
  .text{
    width: 100%;
    height: 50px;
    border-bottom: 2px solid #f0f2f5;
    margin-bottom: 20px;
    font-size: 23px;
  }
  p{
    border-bottom: 1px solid #939292;
    padding-bottom: 5px;
  }

  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>